import { concat, find, filter } from "lodash";
import create from "zustand";
import { devtools, persist } from "zustand/middleware";

import { STORAGE_NAMES } from "~/modules/storage/storage-names";
import { Storage } from "~/utils/localStorage";

export interface StoreRecord {
  name: string;
  flight: string;
  param: string;
  createdAt: string;
  updateAt: string;
}
export interface StoreRecordState {
  records: StoreRecord[];
}

export interface StoreRecordActions {
  create: () => void;
  add: (record: StoreRecord) => void;
  update: () => void;
  has: (flight: string, param: string) => boolean;
  del: (key: string) => void;
  getRemotePath: (flightIds: string[], params: string[]) => void;
}

const initState = (): StoreRecordState => {
  return {
    records: [],
  };
};

export const useStoreRecordStore = create<
  StoreRecordState & StoreRecordActions
>(
  // @ts-ignore
  devtools(
    persist(
      (set, get, api) => ({
        ...initState(),
        create: () => {
          set({ records: [] });
        },
        add: (record) => {
          set({ records: concat(get().records, [record]) });
        },
        update: () => {
          // set({ user: undefined, authenticated: false });
        },
        has: (flight: string, param: string) => {
          const records: StoreRecord[] =
            Storage.get(STORAGE_NAMES.INDEXDB.name)?.state?.records || [];
          const record = find(records, (r: StoreRecord) => {
            return r.flight === flight && r.param === param;
          });
          return !!record;
        },
        del: (key: string) => {
          let records: StoreRecord[] = get().records;
          records = filter(records, (r: StoreRecord) => {
            return r.name !== key;
          });
          set({ records });
        },
        getRemotePath: (flightIds: string[], params: string[]) => {},
      }),
      {
        name: STORAGE_NAMES.INDEXDB.name,
        version: STORAGE_NAMES.INDEXDB.version,
      }
    )
  )
);

export const useStoreRecord = () => {
  const { add, update, del, has } = useStoreRecordStore();
  return {
    add,
    update,
    del,
    has,
  };
};
